package cn.huaqingcheng.tianshu.core.start.service;

import cn.huaqingcheng.tianshu.core.start.model.SiteGroup;
import cn.huaqingcheng.tianshu.core.start.param.SortParam;
import cn.huaqingcheng.tianshu.core.start.repository.SiteGroupRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * SiteGroupServiceImpl
 */
@Service
@RequiredArgsConstructor
public class SiteGroupServiceImpl implements SiteGroupService {

    private final SiteGroupRepository siteGroupRepository;


    @Override
    @Transactional(readOnly = true)
    public List<SiteGroup> getAll(Long accountId) {
        return siteGroupRepository.getAll(accountId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createGroup(SiteGroup data, Long accountId) {
        data.setAccountId(accountId);
        return siteGroupRepository.save(data.populateDefaultValues());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGroup(SiteGroup data, Long accountId) {
        siteGroupRepository.selectById(Objects.requireNonNull(data.getId()))
                .filter(i -> Objects.equals(i.getAccountId(), accountId))
                .orElseThrow(() -> new RuntimeException(String.valueOf(data.getId())));
        siteGroupRepository.update(data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSort(List<SortParam> params, Long accountId) {
        if (params.isEmpty()) {
            return;
        }
        List<Long> ids = params.stream()
                .map(SortParam::id)
                .toList();
        Map<Long, SiteGroup> mapping = siteGroupRepository.selectMapByIds(ids);

        List<SiteGroup> list = params.stream()
                .map(param -> {
                    var group = mapping.get(param.id());
                    if (group == null || !Objects.equals(group.getAccountId(), accountId)) {
                        return null;
                    }
                    return group.setSort(param.sort());
                })
                .filter(Objects::nonNull)
                .toList();
        siteGroupRepository.update(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(Long id, Long accountId) {
        siteGroupRepository.selectById(Objects.requireNonNull(id))
                .filter(i -> Objects.equals(i.getAccountId(), accountId))
                .orElseThrow(() -> new RuntimeException(String.valueOf(id)));
        siteGroupRepository.deleteById(id);
    }

}
